package whu.cachhe.makeorder.ui;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

import whu.cachhe.makeorder.R;
import whu.cachhe.makeorder.net.HttpRequest;
import whu.cachhe.makeorder.net.URLConstant;
import whu.cachhe.makeorder.util.BitmapUtil;
import whu.cachhe.makeorder.util.DateTimeUtil;
import whu.cachhe.makeorder.util.Logger;

/**
 * Created by CocoAdapter on 2018/3/4.
 */

public class ReportActivity extends AppCompatActivity {
    private TextView tvAction;
    private EditText etDescription, etCarNum;
    private ImageView img1, img2, img3;
    private Button btnSubmit;

    private String lotId;

    private static final String[] actions = new String[]{"违规占用", "超时未至"};

    // index 和 code 一一对应
    private File[] files;
    private static final int REQUEST_CAMERA_IMG1_CODE = 0;
    private static final int REQUEST_CAMERA_IMG2_CODE = 1;
    private static final int REQUEST_CAMERA_IMG3_CODE = 2;
    private static final int MAX_UPLOAD_FILE_NUM = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        lotId = getIntent().getStringExtra("lotId");
        if (!TextUtils.isEmpty(lotId))
            init();
    }

    private void init() {
        setContentView(R.layout.activity_report);
        TextView tvTitle = findViewById(R.id.tv_title);
        tvTitle.setText("违规举报");

        tvAction = findViewById(R.id.tv_action);
        etDescription = findViewById(R.id.et_description);
        etCarNum = findViewById(R.id.et_car_num);

        img1 = findViewById(R.id.img_1);
        img2 = findViewById(R.id.img_2);
        img3 = findViewById(R.id.img_3);

        btnSubmit = findViewById(R.id.btn_submit);

        files = new File[MAX_UPLOAD_FILE_NUM];

        initListener();
    }

    private void initListener() {
        View.OnClickListener ocl = new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (v.getId()) {
                    case R.id.tv_action:
                        new AlertDialog.Builder(ReportActivity.this)
                                .setSingleChoiceItems(actions, 0, new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        tvAction.setText(actions[which]);
                                        dialog.dismiss();
                                    }
                                })
                                .create().show();
                        break;
                    case R.id.img_1:
                        useCamera(files, REQUEST_CAMERA_IMG1_CODE);
                        break;
                    case R.id.img_2:
                        useCamera(files, REQUEST_CAMERA_IMG2_CODE);
                        break;
                    case R.id.img_3:
                        useCamera(files, REQUEST_CAMERA_IMG3_CODE);
                        break;
                    case R.id.btn_submit:
                        reportParking(lotId, files);
                        break;
                }
            }
        };
        tvAction.setOnClickListener(ocl);
        img1.setOnClickListener(ocl);
        img2.setOnClickListener(ocl);
        img3.setOnClickListener(ocl);
        btnSubmit.setOnClickListener(ocl);
    }

    private String checkAndGet(TextView tv){
        CharSequence csTem = tv.getText();
        return csTem == null ? null : csTem.toString();
    }

    private String checkAndGet(EditText et){
        Editable etTem = et.getText();
        return etTem == null ? null : etTem.toString();
    }

    private void reportParking(String lotId, File[] files) {
        boolean flag = true;
        String behavior, carNum, description;

        behavior = checkAndGet(tvAction);
        carNum = checkAndGet(etCarNum);
        description = checkAndGet(etDescription);

        if (TextUtils.isEmpty(behavior)){
            Toast.makeText(ReportActivity.this, "请选择违规类型", Toast.LENGTH_LONG).show();
            flag = false;
        } else if (TextUtils.isEmpty(carNum)){
            etCarNum.requestFocus();
            Toast.makeText(ReportActivity.this, "请输入违规车辆车牌号", Toast.LENGTH_LONG).show();
            flag = false;
        } else if (files == null || files.length == 0){
            Toast.makeText(ReportActivity.this, "请拍摄违规现场照片", Toast.LENGTH_LONG).show();
            flag = false;
        }

        if (!flag)
        return;

        try {
            JSONObject fparam = new JSONObject();
            fparam.put("uid", MainActivity.user.getReserveSysId())
                    .put("lotId", lotId)
                    .put("behavior", behavior)
                    .put("carNum", carNum)
                    .put("description", description);

            HttpRequest.post(URLConstant.HOST, "reportViolation", fparam, files, new HttpRequest.HttpRequestCallback() {
                @Override
                public void onSuccess(JSONObject response) {
                    if (response.optInt("success") == 1) {
                        JSONObject jResult = response.optJSONObject("result");
                        String reportId = jResult.optString("reportId");

//                            TODO
                        Logger.e(reportId);

                        Toast.makeText(ReportActivity.this, "举报成功", Toast.LENGTH_LONG).show();
                        finish();
                    } else {
                        Toast.makeText(ReportActivity.this, response.optString("result"), Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onFailure() {
                    Toast.makeText(ReportActivity.this, "网络异常", Toast.LENGTH_LONG).show();
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private void useCamera(File[] files, int requestCode) {
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (intent.resolveActivity(getPackageManager()) != null) {
            files[requestCode] = new File(Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/test/" + System.currentTimeMillis() + ".jpg");
            files[requestCode].getParentFile().mkdirs();

            //注意和xml中的一致
            Uri uri = FileProvider.getUriForFile(this, "whu.cachhe.makeorder.fileprovider", files[requestCode]);
            //添加权限
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
            startActivityForResult(intent, requestCode);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // 拍照
        if (requestCode >= REQUEST_CAMERA_IMG1_CODE && requestCode <= REQUEST_CAMERA_IMG3_CODE){
            if (resultCode == RESULT_OK) {
                switch (requestCode) {
                    case REQUEST_CAMERA_IMG1_CODE:
                        Glide.with(ReportActivity.this).load(
                                FileProvider.getUriForFile(ReportActivity.this, "whu.cachhe.makeorder.fileprovider",
                                        files[REQUEST_CAMERA_IMG1_CODE])).into(img1);
                        //在手机相册中显示刚拍摄的图片
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                                .setData(Uri.fromFile(files[REQUEST_CAMERA_IMG1_CODE])));
                        break;
                    case REQUEST_CAMERA_IMG2_CODE:
                        Glide.with(ReportActivity.this).load(
                                FileProvider.getUriForFile(ReportActivity.this, "whu.cachhe.makeorder.fileprovider",
                                        files[REQUEST_CAMERA_IMG2_CODE])).into(img2);
                        //在手机相册中显示刚拍摄的图片
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                                .setData(Uri.fromFile(files[REQUEST_CAMERA_IMG2_CODE])));
                        break;
                    case REQUEST_CAMERA_IMG3_CODE:
                        Glide.with(ReportActivity.this).load(
                                FileProvider.getUriForFile(ReportActivity.this, "whu.cachhe.makeorder.fileprovider",
                                        files[REQUEST_CAMERA_IMG3_CODE])).into(img3);
                        //在手机相册中显示刚拍摄的图片
                        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)
                                .setData(Uri.fromFile(files[REQUEST_CAMERA_IMG3_CODE])));
                        break;
                }
            }
        } else
            super.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        finish();
    }
}
